package com.example.npercentcalculator;

import java.text.NumberFormat;

import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;

public class AddCommaTextWatcher implements TextWatcher {
	/**
	 * Indicates the change was caused by ourselves.
	 */
	private boolean mSelfChange = false;

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		if (mSelfChange)
			return;
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if (mSelfChange)
			return;
	}

	@Override
	public synchronized void afterTextChanged(Editable s) {
		if (mSelfChange) {
			// Ignore the change caused by s.replace().
			return;
		}

		String formatted = null;

		if (s.length() > 0) {
			NumberFormat nf = NumberFormat.getInstance();
			String userInput = "" + s.toString().replaceAll("[^\\d]", "");
			formatted = String.valueOf(nf.format(Float.parseFloat(userInput)));
		}
		if (formatted != null) {
			mSelfChange = true;
			s.setFilters(new InputFilter[] {});
			s.replace(0, s.length(), formatted, 0, formatted.length());
			mSelfChange = false;
		}
	}
}
